package com.hdq.service.impl;

import com.hdq.mapper.RoleRuleMapper;
import com.hdq.mapper.RuleMapper;
import com.hdq.service.ManagerService;
import com.hdq.service.RuleService;
import dto.RuleAddDTO;
import dto.RuleEditDTO;
import entity.Rule;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vo.RuleInfoVO;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RuleServiceImpl implements RuleService {

    @Autowired
    private RoleRuleMapper roleRuleMapper;
    @Autowired
    private RuleMapper ruleMapper;
    @Override
    public List<RuleInfoVO> select() {
        List<Rule> rule_list=ruleMapper.getRuleInfo();
        return rulesTransformMenus(rule_list);
    }

    @Override
    public void insert(RuleAddDTO ruleAddDTO) {
        Rule rule = new Rule();
        BeanUtils.copyProperties(ruleAddDTO,rule);
        rule.setStatus(1);
        ruleMapper.insert(rule);
    }

    @Override
    public void delete(Long id) {
        ruleMapper.delete(id);
    }

    @Override
    public void update(Long id, RuleEditDTO ruleEditDTO) {
        Rule rule = new Rule();
        BeanUtils.copyProperties(ruleEditDTO,rule);
        rule.setId(id);
        ruleMapper.update(rule);
    }

    private List<RuleInfoVO> rulesTransformMenus(List<Rule> rules) {
//        rule转为ruleVo
        List<RuleInfoVO> ruleInfoVOs = rules.stream().map(this::convertToVO).collect(Collectors.toList());
        List<RuleInfoVO> rootNodes = new ArrayList<>();
        Map<Long, RuleInfoVO> ruleMap = ruleInfoVOs.stream().collect(Collectors.toMap(RuleInfoVO::getId, vo -> vo));

        // 创建一个 List 来存储顶级节点

        for (RuleInfoVO ruleInfoVo : ruleInfoVOs) {
            if (ruleInfoVo.getRuleId() == 0) {
                rootNodes.add(ruleInfoVo);
                continue;
            }
//            寻找父亲节点
            RuleInfoVO parent = ruleMap.get(ruleInfoVo.getRuleId());
//            如果父亲节点不为null
            if (parent != null) {
                if (parent.getChild() == null) {
                    parent.setChild(new ArrayList<>());
                }

                parent.getChild().add(ruleInfoVo);
            }
        }

        return rootNodes;
    }

    private RuleInfoVO convertToVO(Rule rule) {
        RuleInfoVO ruleInfoVO = new RuleInfoVO();
        BeanUtils.copyProperties(rule, ruleInfoVO);
        return ruleInfoVO;
    }
}
